<template>
    <div>
        <h2>留言板</h2>

        <!-- 留言输入表单 -->
        <div>
            <label for="message">输入留言：{{ message }}</label>
            <textarea id="message" placeholder="请输入留言..." v-model="message" @input="checkLength"></textarea>
            <p>剩余字符：{{ jisuanzifu }}</p>
            <button @click="tijiao">提交留言</button>
        </div>

        <!-- 留言列表 -->
        <ul v-show="messages[0] != ''">
            <!-- 留言条目 -->
            <li v-for="(item, index) in messages" :key="index">
                <MessageItem :message="item" v-on:remsg="remsg(index)">
                    <!-- 自定义留言显示的插槽 -->
                    <template v-slot:default>
                        <span>{{ `留言${index + 1}:` }}</span>
                        <span>{{ item }}</span>
                    </template>
                </MessageItem>
            </li>
        </ul>
    </div>
</template>

<script setup lang='ts'>
import { computed, ref } from 'vue';
import MessageItem from './3.1.vue'

const message = ref('')
const messages = ref([''])
const sonmessage = ref('')

const jisuanzifu = computed(() => {
    return 100 - message.value.length
})

const checkLength = () => {
    if (message.value.length > 100) {
        message.value = message.value.substring(0, 100);
    }
};

const tijiao = () => {
    if (messages.value[0] === '') {
        messages.value[0] = message.value
    } else {
        messages.value.push(message.value)
    }
    sonmessage.value = JSON.parse(JSON.stringify(message.value))
}

const remsg = (num: number) => {
    messages.value.splice(num, 1)
}

</script>

<style scoped>
div {
    margin-bottom: 20px;
}

label {
    display: block;
    margin-bottom: 5px;
}

textarea {
    width: 100%;
    height: 100px;
    padding: 8px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    resize: none;
}

button {
    background-color: #28a745;
    color: white;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
    border-radius: 4px;
}

button:hover {
    background-color: #218838;
}

p {
    margin-top: 0;
    font-size: 0.9em;
    color: #888;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #f9f9f9;
}
</style>